package com.jsoft.aop;

import com.jsoft.annotation.Captcha;
import com.jsoft.constant.Constants;
import com.jsoft.controller.Code;
import com.jsoft.core.RedisTemplate;
import com.jsoft.exception.BusinessException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.Map;

/**
 * 校验手机验证码
 */
@Aspect
@Component
public class CaptchaAspect {
    @Resource
    private RedisTemplate redisTemplate;


    @Before("@annotation(captcha)")
    public void doBefore(JoinPoint joinPoint, Captcha captcha) {
        //获取所有参数值
        Object args[] = joinPoint.getArgs();
        //获取方法签名
        Map<String, String> userData = (Map) args[0];
        System.out.println(userData);
        String phone = userData.get("phone");
        String token = userData.get("token");
        String phoneCaptcha = userData.get("phoneCaptcha");
        String result = redisTemplate.get(Constants.CAPTCHA_PREFIX + phone + ":" + token);
        //验证码校验
        if(phoneCaptcha.isEmpty()){
             throw new BusinessException("手机验证码为空", Code.GET_ERR);
        }
        if (result == null) {
            throw new BusinessException("手机验证码已过期", Code.GET_ERR);
        } else if (!result.equals(phoneCaptcha)) {
            throw new BusinessException("手机验证码错误", Code.GET_ERR);
        }

    }
}
